package com.mercycrazy.springframework.context.support;

import com.mercycrazy.springframework.beans.BeansException;
import com.mercycrazy.springframework.beans.factory.config.BeanPostProcessor;
import com.mercycrazy.springframework.context.ApplicationContext;
import com.mercycrazy.springframework.context.ApplicationContextAware;

/**
 * 不能直接在创建 Bean 时获取 ApplicationContext 属性，所以需要在执行 refresh 时，
 * 将 ApplicationContext 写入一个包装的 BeanPostProcessor 类中
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2022-11-27
 */
public class ApplicationContextAwareProcessor implements BeanPostProcessor {

    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
